exports.plugin = {
  name: 'policiesModel',
  register: (server) => {
    const { mongoose } = server;
    const schema = mongoose.Schema({
      path: String,
      method: String,
      desc: String,
      group: String,
      target: Object,
      effect: {
        type: String,
        default: 'permit',
      },
    });
    schema.methods = {

      // 获取策略总数
      getPoliciesCount() {
        return this.model('policies').countDocuments();
      },
      // 获取策略
      getPolicies({
        page, perPage, searchField, searchValue,
      } = {
        page: 1,
        perPage: 10,
      }) {
        const conditions = {};
        if (searchField && searchValue) {
          conditions[searchField] = { $regex: new RegExp(`.*${searchValue}.*`, 'i') };
        }
        return this.model('policies').find(conditions, { __v: 0 })
          .skip((page - 1) * perPage)
          .limit(perPage)
          .sort({ ctime: -1 });
      },
      // 根据用户组获取策略
      getPoliciesLogined(group) {
        if (group.length !== 0) {
          // 非 admin 用户
          return this.model('policies').find({ group: { $in: group } });
        }
        return this.model('policies').find();
      },

      // 根据id获取策略
      getPolicie(_id) {
        return this.model('policies').findOne({ _id });
      },
      // 添加策略
      addPolicy(data) {
        return this.model('policies').create(data);
      },

      // 根据ID更新策略
      updatePolicy(_id, data) {
        return this.model('policies').updateOne({ _id }, data);
      },

      // 判断字段method, path组合值是否存在
      isExist({
        method, path, group,
      }) {
        return this.model('policies').findOne({
          method, path, group,
        });
      },
      // 根据ID删除策略
      deletePolicyById(_id) {
        return this.model('policies').deleteOne({ _id });
      },
      // 根据method和path获取一条数据
      getPolicyByMethodAndPath({ method, path }) {
        return this.model('policies').find({ method, path });
      },
      // 获取所有的组
      getGroups() {
        return this.model('policies').find({}, { group: 1, _id: 0 }).distinct('group');
      },

    };

    const Policies = mongoose.model('policies', schema);
    server.decorate('request', 'policiesModel', new Policies());
  },
};
